package com.orange.core.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.core.pojo.R;
import com.orange.core.pojo.enums.EErrorCode;
import com.orange.core.util.Constants;
import com.orange.core.util.TokenUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.AccountStatusException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@RequiredArgsConstructor
public class AccountAuthenticationFailHandler<T> implements AuthenticationFailureHandler {

    protected final ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        log.info("账号登录失败：{}", exception.getMessage());
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setHeader(HttpHeaders.CONTENT_TYPE, Constants.APPLICATION_JSON_UTF8_VALUE);
        response.setHeader(Constants.TOKEN_KEY, TokenUtil.getToken(request, true));
        PrintWriter writer = response.getWriter();
        writer.write(objectMapper.writeValueAsString(getFailureR(exception)));
    }

    protected R<T> getFailureR(AuthenticationException exception) {
        if (exception instanceof AccountStatusException) {
            return R.fail(EErrorCode.ACCOUNT_DISABLED);
        } else if (exception instanceof BadCredentialsException) {
            return R.fail(EErrorCode.ACCOUNT_PASSWORD_ERROR, exception.getMessage());
        } else {
            return R.fail(EErrorCode.ACCOUNT_PASSWORD_ERROR, exception.getMessage());
        }
    }
}
